﻿using _111.Models;
using _111.Service.Login.Model;
using Dapper;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using MyDapperApi.Models;
using MyDapperApi.Services.Auth;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json.Nodes;
using static MyDapperApi.Services.DateBaseService;

namespace MyDapperApi.Services.Login;

public class LoginService : ILoginService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IDateBaseService _dateBaseService;
    private readonly IAuthService _authService;

    // 通过依赖注入获取配置，从而读取连接字符串
    public LoginService(IHttpClientFactory httpClientFactory,
        IConfiguration configuration,
        IDateBaseService dateBaseService,
        IAuthService authService)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
        _dateBaseService = dateBaseService;
        _authService = authService;
    }

    /// <summary>
    /// 登录接口
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> Login(LoginRequest request)
    {
        var result = request.Check();

        var Secret = AesCbcHelper.Encrypt(request.Password, System.Text.Encoding.Default.GetBytes("xshAesKey1234567"), System.Text.Encoding.Default.GetBytes("1234567890abcdef"));

        var sqlbuilder = new SqlBuilder();
        var sql = @"SELECT *
                    FROM xsh_user WHERE 1 = 1 AND is_deleted = 0 ";
        sqlbuilder.Add(" AND account = @Account ", "@Account", request.Account);
        sqlbuilder.Add(" AND password = @Password ", "@Password", Secret);

        var entity = await _dateBaseService.QueryFirstOrDefaultAsync<XshUserEntity>(sql, sqlbuilder);

        if (entity != null)
        {
            var token = await _authService.CreateToken(entity.Role,entity.Account);
            result.SetSuccess(token.data);
        }
        else
        {
            result.SetError("用户名或密码错误");
        }

        return result;
    }
}